package com.apop.demo.encrypt.util;

import org.bouncycastle.util.encoders.Base64;

/**
 * @Description:
 * @Author: zjy
 * @Date: 2025/2/18 15:46
 */
public class Base64Utils {
    private static final String BASE64_PATTERN = "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$";

    /**
     * 使用 Bouncy Castle 库进行 Base64 解码
     *
     * @param base64String Base64 编码的字符串
     * @return 解码后的字节数组
     */
    public static byte[] bouncyDecode(String base64String) {
        if (base64String == null || base64String.isEmpty()) {
            throw new IllegalArgumentException("Input string cannot be null or empty");
        }
        // 使用正则表达式验证输入字符串是否为有效的Base64编码
        if (!base64String.matches(BASE64_PATTERN)) {
            throw new IllegalArgumentException("非法的Base64字符串 " + base64String);
        }
        return Base64.decode(base64String);
    }

    public static byte[] encodeToBase64(byte[] data) {
        if (data == null) {
            throw new IllegalArgumentException("Input data cannot be null");
        }
        return Base64.encode(data);
    }

    /**
     * 使用 Bouncy Castle 库进行 Base64 编码
     *
     * @param data 需要编码的字节数组
     * @return Base64 编码后的字符串
     */
    public static String bouncyEncode(byte[] data) {
        if (data == null) {
            throw new IllegalArgumentException("Input data cannot be null");
        }
        return new String(Base64.encode(data));
    }
}
